<template>
  <el-avatar :src="avatarUrl" :key="avatarKey" />
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { getUserAvatarBlobUrl, getUserAvatarFileName } from '../utils/avatar'

const props = defineProps({
  avatarKey: {
    type: [String, Number],
    default: null
  }
})

const avatarUrl = ref('')
const avatarKey = ref(Date.now())

const loadAvatar = async () => {
  const userId = localStorage.getItem('userId')
  // 先查头像文件名
  const fileName = await getUserAvatarFileName(userId)
  // 再用blob url方式加载头像
  const newUrl = await getUserAvatarBlobUrl(fileName)
  avatarUrl.value = newUrl
  avatarKey.value = Date.now()
}

// 监听localStorage变化，当头像更新时触发刷新
const handleStorageChange = (e) => {
  if (e.key === 'avatarUpdated') {
    console.log('检测到头像更新事件，重新加载头像')
    loadAvatar()
  }
}

onMounted(() => {
  loadAvatar()
  window.addEventListener('storage', handleStorageChange)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('storage', handleStorageChange)
})

// 监听avatarKey的变化，重新加载头像
watch(() => props.avatarKey, () => {
  loadAvatar()
}, { immediate: false })

// 暴露刷新方法给父组件
defineExpose({
  refresh: loadAvatar
})
</script>

<style scoped>
.avatar-image {
  border-radius: 50%;
  object-fit: cover;
  width: 48px;
  height: 48px;
}
</style> 